package com.runshu.newsmartark.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.ProStockAdapter;
import com.runshu.newsmartark.adapter.SearchDtaAdapter;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.entity.ProductsBean;
import com.runshu.newsmartark.entity.SearchInfoEntity;
import com.runshu.newsmartark.mvp.contract.ProductDtaContract;
import com.runshu.newsmartark.mvp.contract.SearchDtaContract;
import com.runshu.newsmartark.mvp.model.ProductDtaModel;
import com.runshu.newsmartark.mvp.model.SearchDtaModel;
import com.runshu.newsmartark.mvp.presenter.ProductDtaPresenter;
import com.runshu.newsmartark.mvp.presenter.SearchDtaPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.util.KeyBoardUtils;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.TopTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/11/4
 * @decs：搜索产品
 */

public class SearchDtaActivity extends BaseActivity implements SearchDtaContract.View, ProductDtaContract.View {
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.searchEdit)
    SearchView mSearchEdit;
    @BindView(R.id.recy_info)
    RecyclerView mRecyInfo;
    SearchDtaAdapter searchDtaAdapter;
    @BindView(R.id.recy_search)
    RecyclerView mRecySearch;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    private List<SearchInfoEntity> searchInfoList;
    private SearchDtaPresenter searchDtaPresenter;
    private ProductDtaPresenter dtaPresenter;
    private String mac;
    private List<ProductsBean> mData;
    private ProStockAdapter mAdapter;
    private boolean isLoadMore = false;
    private int pageSize = 20;
    private int pageNum = 1;
    private String proName;

    @Override
    protected int getLayoutId() {
        return R.layout.act_search_data;
    }

    @Override
    protected void initView() {
        mToolbar.setIsShowBac( true );
        mToolbar.setTitle( "搜索商品" );
        mac = MacUtils.getFormatMacAddr();
        searchDtaPresenter = new SearchDtaPresenter( this, new SearchDtaModel() );
        searchInfoList = new ArrayList<>();
        searchDtaAdapter = new SearchDtaAdapter( searchInfoList );
        dtaPresenter = new ProductDtaPresenter( this, new ProductDtaModel() );
        mRecyInfo.setLayoutManager( new LinearLayoutManager( context ) );
        mRecyInfo.setAdapter( searchDtaAdapter );
        searchDtaAdapter.bindToRecyclerView( mRecyInfo );
/**
 * 默认情况下是没提交搜索的按钮，所以用户必须在键盘上按下"enter"键来提交搜索.你可以同过setSubmitButtonEnabled(
 * true)来添加一个提交按钮（"submit" button)
 * 设置true后，右边会出现一个箭头按钮。如果用户没有输入，就不会触发提交（submit）事件
 */
        mSearchEdit.setSubmitButtonEnabled( true );
        mData = new ArrayList<>();
        mAdapter = new ProStockAdapter( mData );
        mRecySearch.setLayoutManager( new LinearLayoutManager( context ) );
        mRecySearch.setAdapter( mAdapter );
        mAdapter.bindToRecyclerView( mRecySearch );
        mAdapter.setEmptyView( R.layout.empty_view );


        mSearchEdit.setIconifiedByDefault( true );
        mSearchEdit.setFocusable( true );
        mSearchEdit.setIconified( false );
        mSearchEdit.requestFocusFromTouch();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void bindListener() {
        searchDtaAdapter.setOnItemClickListener( new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                proName = searchInfoList.get( position ).getField();
                mSearchEdit.setQuery(proName,false);
                mRecyInfo.setVisibility( View.GONE );
                mRecySearch.setVisibility( View.VISIBLE );
                KeyBoardUtils.closeKeybord( mSearchEdit, context );
                isLoadMore = false;
                pageNum = 1;
                dtaPresenter.getProductInfo( proName, mac, pageSize, pageNum );

            }
        } );

        mSearchEdit.setOnQueryTextListener( new SearchView.OnQueryTextListener() {
            @Override
            //输入完成后，提交时触发的方法，一般情况是点击输入法中的搜索按钮才会触发，表示现在正式提交了
            public boolean onQueryTextSubmit(String query) {

                if (TextUtils.isEmpty( query )) {
                    ToastUtils.showText( "请输入查找内容！" );
                } else {
                    KeyBoardUtils.closeKeybord( mSearchEdit, context );
                    proName = query;
                    mRecyInfo.setVisibility( View.GONE );
                    mRecySearch.setVisibility( View.VISIBLE );
                    isLoadMore = false;
                    pageNum = 1;
                    dtaPresenter.getProductInfo( proName, mac, pageSize, pageNum );
                }
                return true;

            }

            @Override
            public boolean onQueryTextChange(String newText) {
                mRecyInfo.setVisibility( View.VISIBLE );
                mRecySearch.setVisibility( View.GONE );
                searchDtaPresenter.getSearchTitle( newText, mac );
                return true;
            }
        } );
        mSearchEdit.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchEdit.onActionViewExpanded();
            }
        } );

        mSwipeLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                dtaPresenter.getProductInfo( proName, mac, pageSize, pageNum );
            }
        } );

        mAdapter.setOnLoadMoreListener( new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                dtaPresenter.getProductInfo( proName, mac, pageSize, pageNum );

            }
        } );
        mSwipeLayout.setRefreshing( true );
        mSwipeLayout.post( () -> {
            dtaPresenter.getProductInfo( proName, mac, pageSize, pageNum );

        } );

    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @Override
    public void onGetSearchTitleSuccess(ResponseBean responseBean) {
        searchInfoList = (List<SearchInfoEntity>) responseBean.pullData();
        searchDtaAdapter.setNewData( searchInfoList );
    }

    @Override
    public void onGetProductSuccess(ResponseBean responseBean) {
        mSwipeLayout.setRefreshing( false );//完成刷新
        mData = (List<ProductsBean>) responseBean.pullData();
        if (mData == null) {
            return;
        }
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData( mData );//加载更多的数据，add进去
            } else {
                mAdapter.setNewData( mData );//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore( true );//允许加载更多
            } else {
                if (pageNum == 1) {
                    //数据得清空才会显示空布局
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                }
                mAdapter.loadMoreEnd( true );//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            mAdapter.setNewData( mData );
        }

    }

    @Override
    public void onError(String msg) {
        ToastUtils.showText( msg );

    }


}